<?php
/*
 * Copyright (c) 2022.  Liuhongbin All rights reserved.
 * @domain http://dkyx.cc
 * @author liuhongbin <514660094@qq.com>
 */

namespace app\controller\adminapi\platform\app;

use app\controller\adminapi\platform\PlatformController;
use app\common\model\addon\Addons;
use app\common\model\platform\Platform;
use app\common\model\platform\PlatformApp;
use hiduoke\services\CloudServer;
use hiduoke\services\FormBuilder as Form;
use think\App;
use think\Exception;
use think\facade\Cache;
use think\Request;

class MinApp extends PlatformController
{
    /**
     * @var PlatformApp
     */
    public $model;

    public function __construct(App $app, PlatformApp $model)
    {
        parent::__construct($app);
        $this->model = $model;
    }

    /**
     * 显示小程序列表
     * @Route("min_app", method="GET")
     * @return \think\Response
     */
    public function index()
    {
        return $this->success("ok");
    }

    /**
     * 显示创建小程序表单页.
     * @Route("min_app/create", method="GET")
     * @return \think\Response
     */
    public function create()
    {
        $rule = array();
        //创建表单
        $form = Form::createForm("/adminapi/platform/min_app/index")->setMethod("POST");
        //新增表单
        $rule[] = Form::input('name', '小程序集合名称', "")->required();
        $rule[] = Form::dkImage('logo', '图标', "");
        $rule[] = Form::input('sort', '排序', "0");
        $rule[] = Form::input('description', '描述', "");
        $form->setTitle("新增小程序集合名称")->setRule($rule);
        return $this->success("", Form::getFormData($form));
    }

    /**
     * 保存新建
     * @Route("min_app", method="POST")
     * @param \think\Request $request
     * @return \think\Response
     */
    public function save(Request $request)
    {
        $wallet = $this->userInfo['wallet'];
        if ($wallet['min_app'] <= $wallet['use_count']['min_app'] && !$this->userInfo['is_admin']) {
            return $this->error("创建次数不足");
        }
        $formData = $request->post('formData', []);
        $platform = new Platform();
        $platform_data = array(
            "type"        => 2,
            "uid"         => $this->userInfo['uid'],
            "name"        => $formData['name'],
            "description" => $formData['description'],
            "logo"        => $formData['logo'],
            "sort"        => $formData['sort'],
        );
        $platform->save($platform_data);
        return $this->success("新增成功", ['plaid' => $platform->plaid]);
    }

    /**
     * 显示编辑小程序表单页.
     * @Route("min_app/id/edit", method="GET")
     * @param int $id
     * @return \think\Response
     */
    public function edit($id)
    {
        $rule = array();
        //创建表单
        $platform = new Platform();
        $row = $platform->where(['plaid' => $id])->find();
        if (!$row) {
            return $this->error("当前平台不存在");
        }
        $form = Form::createForm("/adminapi/platform/min_app/index/" . $id)->setMethod("PUT");
        //新增表单
        $rule[] = Form::input('name', '小程序集合名称', $row->name)->required();
        $rule[] = Form::dkImage('logo', '图标', $row->logo);
        $rule[] = Form::input('sort', '排序', $row->sort);
        $rule[] = Form::input('description', '描述', $row->description);
        $form->setTitle("编辑小程序集合")->setRule($rule);
        return $this->success("", Form::getFormData($form));
    }

    /**
     * 保存更新的小程序
     * @Route("min_app/id", method="PUT")
     * @param \think\Request $request
     * @param int $id
     * @return \think\Response
     */
    public function update(Request $request, $id)
    {
        $formData = $request->post('formData', []);
        $platform = new Platform();
        $platform_data = $platform->where(['plaid' => $id])->find();
        if (!$platform_data) {
            return $this->error("当前平台不存在");
        }
        $platform_data->save([
            "type"        => 2,
            "name"        => $formData['name'],
            "description" => $formData['description'],
            "logo"        => $formData['logo'],
            "sort"        => $formData['sort'],
        ]);
        return $this->success("编辑成功");
    }

    /**
     * 获取添加应用列表
     */
    public function getAddonsOption($plaid = 0, $isApi = true)
    {
        $options = [];
        $names = [];
        foreach ($this->model->where(['plaid' => $plaid])->select() as $key => $value) {
            $names[] = $value['addon_name'];
        }
        $addons = (new Addons())->whereIn('name', $names)->select();
        foreach ($addons as $key => $value) {
            $options[] = [
                'value' => $value['name'],
                'label' => $value['title']
            ];
        }
        if ($isApi) {
            return $this->success('', $options);
        } else {
            return $options;
        }
    }

    public function getAddonAppOption($plaid = 0, $isApi = true)
    {
        $search = input('search', '');
        $where = [];
        if ($search) {
            $where = [['name', 'like', "%" . $search . "%"]];
        }
        $options = [];
        // TODO 这里需要连表查询
        $apps = (new PlatformApp())
            ->where(['plaid' => $plaid])
            ->where($where)
            ->append(['addon'])
            ->limit(0, 10)
            ->select();
        foreach ($apps as $key => $value) {
            $options[] = [
                'value' => $value['id'],
                'label' => $value['name'] ?: $value['addon']['title'],
                'logo'  => $value['logo'] ?: $value['addon']['icon'],
            ];
        }
        if ($isApi) {
            return $this->success('', $options, $this->model->getLastSql());
        } else {
            return $options;
        }
    }

    /**
     * 切换小程序
     * @param $appid
     * @return \think\response\Json
     */
    public function changeDefaultApp($appid)
    {
        $res = (new PlatformApp())->where(['id' => $appid])->find();
        if (!$res) {
            return $this->error('切换失败，当前小程序不存在');
        } else {
            (new Platform())->where(['plaid' => $res['plaid']])->update(['default_app_id' => $appid]);
            return $this->success('切换成功');
        }
    }


    public function deleteApp($appid)
    {
        $user = $this->userInfo;
        if (!$user['is_admin']) {
            return $this->error('无权限删除');
        }
        $app = (new PlatformApp())->where(['id' => $appid])->find();
        if (!$app) {
            return $this->error('删除失败，当前小程序不存在');
        } else {
            $token = $app['token'];
            if ($token != 'local') {
                try {
                    // 云端删除对应数据
                    (new CloudServer())->deleteSiteAddonToken($app['addon_name'], $token, $app['plaid']);
                } catch (Exception $e) {
                }
            }
            $app->delete();
            event($app['addon_name'] . "_app_delete", $appid);
            Cache::delete('getSiteAddonTokenCount');
            return $this->success("删除成功");
        }
    }

    /**
     * 获取当前默认应用
     * @param $plaid
     * @return \think\response\Json
     */
    public function getDefaultApp($plaid = 0, $appid = 0)
    {
        $platform = (new Platform())->where(['plaid' => $plaid])->find();
        if (!$platform) {
            return $this->error('平台有误');
        }
        if ($appid) {
            $addon_app = (new PlatformApp())->where(['id' => $appid])->append(['addon'])->find();
        } else {
            $addon_app = (new PlatformApp())->where(['id' => $platform['default_app_id']])->append(['addon'])->find();
        }
        if (!$addon_app) {
            $addon_app = (new PlatformApp())->where(['plaid' => $plaid])->append(['addon'])->find();
            if (!$addon_app) {
                return $this->success('no_default');
            } else {
                // 修改默认
                $platform->default_app_id = $addon_app['id'];
                $platform->save();
            }
        }
        $addon_app['name'] = $addon_app['name'] ?: $addon_app['addon']['title'];
        $addon_app['logo'] = $addon_app['logo'] ?: $addon_app['addon']['icon'];
        return $this->success('', $addon_app);
    }

    /**
     * 获取小程序表单
     * @return \think\response\Json
     * @throws \FormBuilder\Exception\FormBuilderException
     */
    public function getAppForm($plaid = 0)
    {
        $platform = (new Platform())->where(['plaid' => $plaid])->find();
        $default_app_id = $platform['default_app_id'] ?? 0;
        if (!$default_app_id) {
            return $this->error('没有添加应用');
        }
        $row = $this->model->where(['id' => $platform['default_app_id']])->append(['addon'])->find();
        if (!$row) {
            return $this->error('默认应用不存在');
        }
        $rule = array();
        //创建表单
        $form = Form::createForm("/adminapi/platform/min_app/index/saveApp")->setMethod("POST");
        //新增表单
        $col = Form::col()->span(11)->offset(1)->pull(1);
        $rule[] = Form::switches('index', '首页显示', strval($row->index))->col($col)->effect(['help' => '显示到客户端首页']);
        $rule[] = Form::switches('menu', '菜单显示', strval($row->menu))->col($col)->effect(['help' => '显示到平台左侧列表页']);
        $rule[] = Form::dkImage('logo', '图标', $row['logo'] ?? '')->effect(['help' => '自定义小程序图标,方便区分']);
        $rule[] = Form::input('name', '名称', $row['name'] ?? '')->effect(['help' => '自定义小程序名称,方便区分']);
        if (input('is_admin', 0) && $this->userInfo['is_admin']) {
            $rule[] = Form::input('token', "应用Token", $row['token'] ?? '')->effect(['help' => '平台下的应用Token，请勿随意修改，可能会导致应用部分云端功能无法使用,仅管理员可见']);
        }
        $rule[] = Form::input('sort', '排序', $row['sort']);
        $form->setTitle("设置小程序")->setRule($rule);
        return $this->success("", Form::getFormData($form));
    }

    public function saveApp()
    {
        $formData = $this->request->post('formData', []);
        $min_app_data = $this->model->where(['id' => $formData['id']])->find();
        if (!$min_app_data) {
            return $this->error("当前小程序应用不存在");
        }
        $min_app_data->save([
            "name"     => $formData['name'],
            "original" => $formData['original'],
            "appid"    => $formData['appid'],
            "secret"   => $formData['secret'],
            "logo"     => $formData['logo'],
        ]);
        return $this->success("编辑成功");
    }

    public function getAppSettingForm($plaid = 0, $addon_name = "")
    {
        $platform = (new Platform())->where(['plaid' => $plaid])->find();
        $default_app_id = $platform['default_app_id'] ?? 0;
        if (!$default_app_id) {
            return $this->error('没有添加应用');
        }
        $row = $this->model->where(['id' => $platform['default_app_id']])->append(['addon'])->find();
        $rule = array();
        //创建表单
        $form = Form::createForm("/adminapi/platform/min_app/index/saveAppSetting")->setMethod("POST");
        if ($row['app_type'] == 'dy') {
            $rule[] = Form::input('appid', 'Appid', $row['appid'] ?? '')->effect(['help' => '小程序的appid']);
            $rule[] = Form::input('token', 'Token', $row['token'] ?? '')->effect(['help' => '小程序上传Token']);
            $rule[] = Form::input('email', '登录邮箱', $row['email'] ?? '')->effect(['help' => '抖音开放平台登录邮箱']);
            $rule[] = Form::input('password', '登录密码', $row['password'] ?? '')->effect(['help' => '抖音开放平台登录密码']);
        } else {
            $rule[] = Form::ElAlert()->title('提示')->description("当前该小程序没有配置项");
        }
        $form->setTitle("上传配置")->setRule($rule);
        return $this->success("", Form::getFormData($form));
    }


    public function saveAppSetting()
    {
        $formData = getFormData();
    }
}
